/*
 * @Author: luojianfeng
 * @Date: 2022-12-13 10:26:49
 * @LastEditTime: 2023-03-23 15:07:25
 * @LastEditors: luojianfeng
 * @Description:
 */
import type { RouteRecordRaw } from 'vue-router'
import defaultLayout from '~/layouts/default.vue'
import { createRouter, createWebHashHistory } from 'vue-router'
// 获取modules中的路由规则
// https://cn.vitejs.dev/guide/features.html#glob-import
const modules = import.meta.glob<{ default: any }>(
  ['./**/*.ts', '!./index.ts'],
  { eager: true }
)

// modules routes
const routes: RouteRecordRaw[] = []

Object.keys(modules).forEach((key) => {
  const modulesRoutes = modules[key].default || {}

  let modRoutesList = []
  if (Array.isArray(modulesRoutes)) modRoutesList = [...modulesRoutes]
  else modRoutesList = [modulesRoutes]

  routes.push(...modRoutesList)
})

// 根目录
const rootRoute: RouteRecordRaw = {
  path: '/',
  name: 'root',
  redirect: '/home',
  component: defaultLayout,
  children: [...routes]
}

// 404页面
const notFoundPage: RouteRecordRaw = {
  // vue-router@4的变化，舍弃*通配符
  // 官方文档：https://next.router.vuejs.org/zh/guide/migration/index.html#%E5%88%A0%E9%99%A4%E4%BA%86-%EF%BC%88%E6%98%9F%E6%A0%87%E6%88%96%E9%80%9A%E9%85%8D%E7%AC%A6%EF%BC%89%E8%B7%AF%E7%94%B1
  path: '/:pathMatch(.*)*',
  name: '404',
  component: () => import('@/views/common/404.vue')
}

const router = createRouter({
  // 4. 内部提供了 history 模式的实现。为了简单起见，我们在这里使用 hash 模式。
  history: createWebHashHistory(),
  routes: [rootRoute, notFoundPage] // `routes: routes` 的缩写
})

export default router
